#include "helper/sqlite/stream/Query.h"


namespace helper {
namespace sqlite {
namespace stream {

Query::Query()
{
}
Query::~Query() {
}

QueryResult Query::queryScalar(){
  if(isDbValid() && isSqlValid()){

    std::error_code ec;
    auto && stmt = db().createStatement(sql(), ec);
    if(!stmt || ec){
      return QueryResult::make_error(ec);
    }

    _stmt = std::move(stmt.value());

    if(fbind()){
      if(auto && ec = _stmt.prepareInput(fbind()); ec){
        return QueryResult::make_error(ec);
      }
    }

    return _stmt.query();
  }
  return QueryResult::make_error(std::errc::invalid_argument);
}

QueryResult Query::queryVector(){
  if(isDbValid() && isSqlValid()){

    std::error_code ec;
    auto && stmt = db().createStatement(sql(), ec);
    if(!stmt || ec){
      return QueryResult::make_error(ec);
    }

    _stmt = std::move(stmt.value());

    if(fbind()){
      if(auto && ec = _stmt.prepareInput(fbind()); ec){
        return QueryResult::make_error(ec);
      }
    }

    return _stmt.queryNoNext();
  }
  return QueryResult::make_error(std::errc::invalid_argument);
}

Query & Query::reset() {
  //TODO: how to reset ???  same to Action, Executor ???
  // _stmt.reset();
  // _stmt.clearBindings();
  Stream<Query>::reset();
  return *this;
}
}//namespace stream
}//namespace sqlite
}//namespace helper
